/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.timesoft.base.rightmenubox;

import com.timesoft.common.bean.ResponseCommon;
import com.timesoft.common.convertor.Base64ConvertorUtils;
import com.timesoft.common.security.SecurityMD5;
import com.timesoft.global.webservice.WebServiceClient;
import com.timesoft.hibernate.bean.Customer;
import com.timesoft.webservice.client.base.BaseWebService;
import com.timesoft.zk.common.NavigatorUtil;
import com.timesoft.zk.common.ResourceUtil;
import com.timesoft.zk.common.ctrl.IncludePageWsController;
import com.timesoft.zk.common.ctrl.MainPageWsController;
import com.timesoft.zk.common.event.MainEventWsListener;
import com.timesoft.zk.common.validator.ValidateManager;
import com.timesoft.zk.common.validator.ValidateUtill;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.A;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Html;
import org.zkoss.zul.Include;
import org.zkoss.zul.Textbox;

/**
 *
 * @author sorasaks
 */
public class SigninCtrl extends IncludePageWsController {

    private static final Logger LOG = Logger.getLogger(SigninCtrl.class);

    private static final String REGISTER_MAIN = "/WEB-INF/layouts/defaults/register/register-main.zul";

    private Include contentInc;
    private A linkRegister;

    private Textbox txtEmail;
    private Textbox txtPassword;
    private Checkbox chkSigninAutomatic;
    private Button btnSigninRightBox;
    private Html htmlSignin;

    private static final Base64ConvertorUtils base64 = new Base64ConvertorUtils();
    private static final BaseWebService baseService = WebServiceClient.getBaseService();

    public SigninCtrl() throws Exception {
        super();
    }

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp); //To change body of generated methods, choose Tools | Templates.

        initialEventListener();
    }

    private void initialEventListener() throws Exception {
        linkRegister.addEventListener(Events.ON_CLICK, new linkRegisterEventListener());
        
        txtEmail.addEventListener(Events.ON_FOCUS, new validateEventListener());
        txtEmail.addEventListener(Events.ON_OK, new btnSigninEventListener());
        
        txtPassword.addEventListener(Events.ON_FOCUS, new validateEventListener());
        txtPassword.addEventListener(Events.ON_OK, new btnSigninEventListener());
        
        btnSigninRightBox.addEventListener(Events.ON_CLICK, new btnSigninEventListener());
    }

    private class linkRegisterEventListener extends MainEventWsListener implements EventListener {

        public linkRegisterEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            LOG.debug("::::::::::::: Navigator goto register main page ::::::::::::::::::");
            setTitle(ResourceUtil.getLabel("home.label.register.title", locale));
            contentInc = (Include) desktop.getAttribute(MainPageWsController.ATTRIBUTE_CONTENT_INCLUDE);

            NavigatorUtil nv = new NavigatorUtil(contentInc);
            nv.gotoPage(REGISTER_MAIN);
        }
    }

    private class validateEventListener extends MainEventWsListener implements EventListener {

        public validateEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            htmlSignin.setContent("");
        }
    }

    private class btnSigninEventListener extends MainEventWsListener implements EventListener {

        public btnSigninEventListener() throws Exception {
            super();
        }

        @Override
        public void onEvent(Event t) throws Exception {
            if (validate()) {
                Executions.sendRedirect(contextPath);
            }
        }
    }

    private Boolean validate() throws Exception {
        ValidateManager vm = new ValidateManager();
        ValidateUtill vmUtil = new ValidateUtill(contextPath, null, "#ffffff");

        vm.add(vmUtil.require(txtEmail, htmlSignin, ResourceUtil.getLabel("home.label.signin.validate.empty.email", locale)));
        if(!vm.getResult()) {
            return Boolean.FALSE;
        }
        
        vm.add(vmUtil.require(txtPassword, htmlSignin, ResourceUtil.getLabel("home.label.signin.validate.empty.password", locale)));
        if (vm.getResult()) {
            SecurityMD5 md5 = new SecurityMD5(txtPassword.getValue());
            
            ResponseCommon common = (ResponseCommon) base64.stringToGenericObj(baseService.customerCoreGetCustomerByEmailAndPassword(
                    base64.genericObjToString(txtEmail.getValue()),
                    base64.genericObjToString(md5.encoding()),
                    base64.genericObjToString(Boolean.TRUE)));
            Customer customer = (Customer) base64.stringToGenericObj(common.getValue());

            if (!common.isFlag()) {
                vm.add(vmUtil.addErrorHtml(htmlSignin, 
                        common.getMessage()));
                return Boolean.FALSE;
            }
            
            if (customer == null) {
                vm.add(vmUtil.addErrorHtml(htmlSignin, 
                        ResourceUtil.getLabel("home.label.signin.validate.invalid", locale)));
                return Boolean.FALSE;
            }

            Executions.getCurrent().getSession().setAttribute(MainPageWsController.ATTRIBUTE_CUSTOMER_CODE,
                    customer.getCustomerCode());
            Executions.getCurrent().getSession().setAttribute(MainPageWsController.ATTRIBUTE_AUTHENTIFICATION,
                    Boolean.TRUE);
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }

}
